package nina.yiyou.performance.s11collect.start

import nina.yiyou.performance.s11collect.compute.CollectComputeMapMaker
import nina.yiyou.performance.s11collect.compute.EvalCommentCollector
import nina.yiyou.performance.s11collect.input.CollectFilledReader
import nina.yiyou.performance.s11collect.output.CollectResultGenerator
import nina.yiyou.salary.input.config.ConfigExcelReader
import nina.yiyou.salary.input.util.InputPathResolver
import nina.yiyou.salary.output.ResultMapMaker

import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors

class PerformCollectRunner {

  PerformCollectRunner(Path workshopPath) {
    _workshopPath = workshopPath
  }

  void run() {
    Map globalMap = ConfigExcelReader.create(_workshopPath).read().global()
    Path inDir = InputPathResolver.create(_workshopPath, globalMap, 'in.绩效已填').resolve()

    List<CollectFilledReader.Filler> fillerList = readFillers(inDir)
    List<Map> employResult = makeEmployeeResult(fillerList)

    List commentList = new EvalCommentCollector(fillerList).collectList()
//    commentList.each { println([it.targetName(), it.fillerName(), it.content()].join(' ')) }

    new CollectResultGenerator(_workshopPath, globalMap, employResult, commentList).generate()
  }

  private List<CollectFilledReader.Filler> readFillers(Path inDir) {
    def walker = Files.walk(inDir)
    List result = walker
        .filter { Files.isRegularFile(it) }
        .filter { !it.fileName.toString().startsWith('~$') }
        .map { new CollectFilledReader(it).read() }
        .collect(Collectors.toList())

    walker.close()
    return result
  }

  private List<Map> makeEmployeeResult(List<CollectFilledReader.Filler> fillerList) {
    def fillMap = fillerList.collectEntries {
      [it.employeeId(), [
          '工号': it.employeeId(),
          '姓名': it.employeeName(),
          '自评': it.selfEval()[-1].value(),
      ]]
    }

    println('计算额外结果...')
    def computeMap = new CollectComputeMapMaker(fillerList).make()

    return new ResultMapMaker([
        ['已填', fillMap],
        ['计算', computeMap],
    ]).make().values().asList()
  }

  private final Path _workshopPath
}
